<script setup>
import { getList, createApi, updateApi, updateStatusApi, deleteApi, setRules } from '@/api/role'
import { getRuleList } from '@/api/rule'
import { ref, onMounted, nextTick } from 'vue'
import FromDrawer from '@/components/from-drawer.vue'
import { toast } from '@/utils/elnotification'
import ListHeader from '@/components/list-header.vue'

//绑定表格数据
const tableData = ref([])
//总页数
const total = ref(0)
//当前页
const currentPage = ref(1)
//加载动画
const loading = ref(false)
//公告标题
const title1 = ref('')

//获取表格数据
const getData = async (p = null) => {
  if (typeof p === 'number') {
    currentPage.value = p
  }
  loading.value = true
  try {
    const res = await getList(currentPage.value)
    tableData.value = res.list
    total.value = res.totalCount
  } catch (error) {
  } finally {
    loading.value = false
  }
}

//删除公告
const onDelete = async (row) => {
  fromDrawerRef.value.showLoading()
  try {
    await deleteApi(row.id)
    toast('删除成功')
    getData(1)
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    fromDrawerRef.value.hideLoading()
  }
  console.log(row)
}

//新增公告
const fromDrawerRef = ref(null)
const onAdd = () => {
  title1.value = '新增角色'
  fromDrawerRef.value.open()
  form.value = {
    name: '',
    status: 1,
    desc: ''
  }
}

//表单部分
const formRef = ref(null)
const form = ref({
  name: '',
  status: 1,
  desc: ''
})

//表单校验规则
const rules = {
  name: [{ required: true, message: '角色昵称不能为空', trigger: 'blur' }],
  desc: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
}

//确认提交
const onSubmit = async () => {
  const val = await formRef.value.validate((val) => val)
  if (!val) return
  fromDrawerRef.value.showLoading()
  if (changId.value !== 0) {
    try {
      await updateApi(changId.value, { ...form.value })
      toast('编辑成功')
      getData(1)
    } catch (error) {
      toast('编辑失败', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  } else {
    try {
      await createApi({ ...form.value })
      toast('新增成功')
      getData(1)
    } catch (error) {
      toast('新增失败', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  }
}

//修改公告
const changId = ref(0)
const onChange = (row) => {
  title1.value = '修改角色'
  const { id, name, status, desc } = row
  form.value = {
    name,
    status,
    desc
  }
  changId.value = id
  fromDrawerRef.value.open()
}

//修改状态
const onChangeStatus = async (status, row) => {
  row.statusLoading = true
  try {
    await updateStatusApi(row.id, status)
    toast('修改状态成功')
    row.status = status
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    row.statusLoading = false
  }
}

//权限配置
//默认展开
const elTreeRef = ref(null)
const ruleIds = ref([])
const defaultExpandedkeys = ref([])
const treeId = ref(0)
const treeHeight = ref(0)
const ruleList = ref([])
const setRoleDrawerRef = ref(null)
const checkStrictly = ref(false)
const onRoleSubmit = async () => {
  setRoleDrawerRef.value.showLoading()
  try {
    await setRules(treeId.value, ruleIds.value)
    toast('权限配置成功')
    getData()
    setRoleDrawerRef.value.close()
  } catch (error) {
  } finally {
    setRoleDrawerRef.value.hideLoading()
  }
}

const onSetRole = async (item) => {
  treeHeight.value = window.innerHeight - 170
  treeId.value = item.id
  checkStrictly.value = true
  const res = await getRuleList(1)
  ruleList.value = res.list
  defaultExpandedkeys.value = res.list.map((item) => item.id)
  setRoleDrawerRef.value.open()
  ruleIds.value = item.rules.map((o) => o.id)
  setTimeout(() => {
    elTreeRef.value.setCheckedKeys(ruleIds.value)
    checkStrictly.value = false
  }, 150)
}

const onCheck = (...e) => {
  const { checkedKeys, halfCheckedKeys } = e[1]
  ruleIds.value = [...checkedKeys, ...halfCheckedKeys]
}

onMounted(() => {
  getData()
})
</script>

<template>
  <el-card shadow="never" class="border-0" v-loading="loading">
    <ListHeader @create="onAdd" @refresh="getData"></ListHeader>
  </el-card>
  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column prop="name" label="角色名称" />
    <el-table-column prop="desc" label="角色描述" />
    <el-table-column label="状态" width="120">
      <template #default="{ row }">
        <el-switch
          v-model="row.status"
          :active-value="1"
          :inactive-value="0"
          @change="onChangeStatus($event, row)"
          :loading="row.statusLoading"
          :disabled="row.id == 2 || row.id == 3"
        >
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="250" align="center">
      <template #default="scoped">
        <el-button type="primary" size="small" text @click="onSetRole(scoped.row)"
          >配置权限</el-button
        >
        <el-button
          type="primary"
          size="small"
          text
          @click="onChange(scoped.row)"
          v-if="scoped.row.id !== 2 && scoped.row.id !== 3"
          >修改</el-button
        >
        <el-popconfirm
          v-if="scoped.row.id !== 2 && scoped.row.id !== 3"
          title="是否要删除该公告？"
          confirm-button-text="确认"
          cancel-button-text="取消"
          @confirm="onDelete(scoped.row)"
        >
          <template #reference>
            <el-button type="primary" size="small" text>删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <div class="flex justify-center justify-center mt-5">
    <el-pagination
      @current-change="getData"
      :current-page="currentPage"
      background
      layout="prev,pager,next"
      :total="total"
    />
  </div>
  <FromDrawer ref="fromDrawerRef" :title="title1" @submit="onSubmit">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="desc">
        <el-input
          v-model="form.desc"
          placeholder="请输入角色描述"
          type="textarea"
          :rows="5"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0"> </el-switch>
      </el-form-item>
    </el-form>
  </FromDrawer>

  <!-- 权限配置 -->
  <FromDrawer ref="setRoleDrawerRef" title="权限配置" @submit="onRoleSubmit">
    <el-tree-v2
      :check-strictly="checkStrictly"
      node-key="id"
      ref="elTreeRef"
      :default-expanded-keys="defaultExpandedkeys"
      :data="ruleList"
      :props="{ label: 'name', children: 'child' }"
      show-checkbox
      :height="treeHeight"
      @check="onCheck"
    >
      <template #default="{ node, data }">
        <div class="flex flex-1 items-center">
          <el-tag size="small" :type="data.menu ? '' : 'info'">
            {{ data.menu ? '菜单' : '权限' }}
          </el-tag>
          <span class="ml-2 text-xs">{{ data.name }}</span>
        </div>
      </template>
    </el-tree-v2>
  </FromDrawer>
</template>

<style scoped></style>
